<template>
  <div class="addbanner">
     <h4>Banner管理>{{bannerTips}}Banner</h4>
     <div class="container">
        <el-form :model="bannerInfo" status-icon  
                  ref="ruleForm2"  
                  label-width="100px" 
                  class="demo-ruleForm"
                  :rules="rules">
                <el-form-item prop="title" label="标题" class="form-item">
                    <el-input  v-model="bannerInfo.title" placeholder="请输入标题"></el-input>
                </el-form-item>
                <el-form-item label="链接" class="form-item">
                    <el-input   v-model="bannerInfo.link" placeholder="请输入banner链接"></el-input>
                 </el-form-item>
                <el-form-item  prop="usefulDate" label="有效期"  class="form-item">
                    <el-date-picker
                            v-model="bannerInfo.usefulDate"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            value-format="yyyy-MM-dd">
                    </el-date-picker>
                </el-form-item>
                 <el-form-item prop="radio"  label="状态"  class="form-item">
                     <el-radio v-model="bannerInfo.radio" label="1">显示</el-radio>
                     <el-radio v-model="bannerInfo.radio" label="0">不显示</el-radio>
                </el-form-item>
                <el-form-item  label="上传图片" prop="imageUrl">
                       <el-upload
                                action="/api/banner/uploadPics_Base64"
                                list-type="picture-card"
                                accept="image/jpg,image/png,image/jpeg,image/webp,image/gif,image/bmp"
                                :on-preview="handlePictureCardPreview"
                                :on-remove="handleRemove"
                                :before-upload="beforeAvatarUpload"
                                :on-success="handleSuccess"
                                :http-request="httpRequest"
                                :limit="1"
                                :file-list="fileList">
                                <i class="el-icon-plus"></i>
                        </el-upload>
                        <el-dialog :visible.sync="dialogVisible">
                              <img width="100%" :src="dialogImageUrl" alt="">
                        </el-dialog>
                </el-form-item>
                <el-form-item>
                    <el-button @click="cancel()">取消</el-button>
                    <el-button type="primary" @click="submitForm('ruleForm2')" v-if="isSave">保存</el-button>
                </el-form-item>
         </el-form>
     </div>
  </div>
</template>

<script>
import { addBanner,update_banner,bannerDetail,uploadImg } from '@/request/api'
export default {
    data(){
        var checkBlank = (rule, value, callback) => {
            if (/(^\s+)|(\s+$)|\s+/g.test(value)) {
                callback(new Error('请不要输入空格'));
            } else {
                callback()
            } 
        };
        return {
             bannerInfo: {
                    title:'',
                    link:'',
                    usefulDate:'',
                    status:'',
                    radio:'1',
                    imageUrl: ''
             },
             rules: {
                    title: [
                        { required: true, message: '标题不能为空', trigger: 'blur' }
                    ],
                    
                    radio:[
                        { required: true, message: '状态不能为空', trigger: 'change' }
                    ],
                    imageUrl:[
                         { required: true, message: '图片不能为空', trigger: 'change' }
                    ],
                    usefulDate:[
                        { required: true, message: '有效期不能为空', trigger: 'change' }
                    ]
             },
             fileList:[],
             dialogImageUrl: '',
             dialogVisible: false,
             fileReader: '',
             bannerTips:'',
             isSave:true
           
        }
    },
    created(){
       if( this.$route.path.indexOf('/banner/update_banner') != -1  ) {
           //  编辑页面 通过id  渲染页面 
           bannerDetail({
               id:this.$route.params.id
           }).then(res => {
                console.log(res);
                // 数据 回显 
                this.fileList = [{url:res.data.url}];
                this.bannerInfo.title = res.data.title;
                this.bannerInfo.link = res.data.link;
                this.bannerInfo.imageUrl = res.data.url;
                this.bannerInfo.usefulDate = [ res.data.beginTime , res.data.endTime ];
                this.bannerInfo.radio = res.data.state ?  '1' : '0';
           })
           this.bannerTips = '编辑'
           this.isSave = true ;  // 显示保存按钮
       }else if(this.$route.path.indexOf('/banner/detail_banner') != -1 ) {
            //  详情页面
            //  数据 回显 
            bannerDetail({
               id:this.$route.params.id
           }).then(res => {
                console.log(res);
                // 数据 回显 
                this.fileList = [{url:res.data.url}];
                this.bannerInfo.title = res.data.title;
                this.bannerInfo.link = res.data.link;
                this.bannerInfo.usefulDate = [ res.data.beginTime , res.data.endTime ];
                this.bannerInfo.radio = res.data.state ?  '1' : '0';
               
                console.log(this.fileList);
           })
             this.bannerTips = '详情'
              this.isSave = false ;  //不能显示 保存按钮

       }else {
        //    
            this.bannerTips = '新增'
            this.isSave = true ;
       }

    },
    mounted(){
        if (!window.FileReader) {
               console.error('Your browser does not support FileReader API!')
        }
        this.fileReader = new FileReader();
    },
    methods:{
      handleRemove(file, fileList) {
          console.log(file, fileList);
      },
      handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
      },
      beforeAvatarUpload(file) {
                // 文件类型进行判断 
                console.log(file.type);
                 var  isJPG;
                if( file.type == 'image/jpeg') {
                   isJPG = true;
                }
                if(file.type == 'image/png') {
                    isJPG = true;
                } 
               
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isJPG) {
                  this.$message.error("上传头像图片只能是 JPG 或者 PNG 格式!");
                }
                if (!isLt2M) {
                    this.$message.error("上传头像图片大小不能超过 2MB!");
                }
                return isJPG && isLt2M;
      },
      handleSuccess(response, file, fileList) {
         console.log(response);
         console.log(file);
         console.log(fileList);
         this.bannerInfo.imageUrl = fileList[0].url;
      },
      httpRequest(option) {
           console.log(option);
           let file = option.file;
           let filename = file.name;
            if (file) {
                this.fileReader.readAsDataURL(file)
            }
            
            this.fileReader.onload = () => {
                    let base64Str = this.fileReader.result
                    console.log(base64Str)
                    uploadImg({
                        picsBase64Str:base64Str
                    }).then(res => {
                         console.log(res);
                         if(res.code == 1) {
                             this.bannerInfo.imageUrl = res.data;
                         }
                    })
             }
      },
      submitForm(formName) {
          this.$refs[formName].validate( (valid) => {
              if(valid) {
                  if(this.$route.path.indexOf('/banner/update_banner') != -1) {
                    //   修改 接口
                    update_banner({
                        id:this.$route.params.id,
                        title:this.bannerInfo.title,
                        link:this.bannerInfo.link,
                        beginTime:this.bannerInfo.usefulDate[0],
                        endTime:this.bannerInfo.usefulDate[1],
                        url:this.bannerInfo.imageUrl,
                        state:this.bannerInfo.radio
                    }).then(res => { 
                         if(res.code == 1) {
                              this.$message({
                                    type: 'success',
                                    message: '编辑成功!'
                              });
                            this.$router.go(-1);
                         }
                    })
                  }else {
                     // 新增
                     this.add_banner();
                  }
              }
          })
          
      },
      add_banner(){
                addBanner({
                        title:this.bannerInfo.title,
                        link:this.bannerInfo.link,
                        beginTime:this.bannerInfo.usefulDate[0],
                        endTime:this.bannerInfo.usefulDate[1],
                        url:this.bannerInfo.imageUrl,
                        state:this.bannerInfo.radio
                }).then(res => {
                    if(res.code == 1) {
                        this.$message({
                                type: 'success',
                                message: '保存成功!'
                        });
                        this.$router.go(-1);
                    }
                }) 
      },
      cancel(){
          this.$router.go(-1);
      }
    }
 }
</script>
<style  scoped>
.addbanner h4 {
    line-height: 22px;
    border-left: 5px solid rgb(32, 160, 255);
    font-size:16px;
    color: #666;
    padding-left:  10px;
    font-size:18px;
    margin-bottom:20px;
}
.form-item {
    width: 500px;
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>